package gptma.bo.aop;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.persistence.NoResultException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Interceptor
@NoResultFailProof
public class NoResultInterceptor {

	private static final Logger log = LoggerFactory
			.getLogger(NoResultInterceptor.class);

	@AroundInvoke
	public Object noResult(InvocationContext invocationContext)
			throws Exception {
		Object ret = null;
		Method method = invocationContext.getMethod();
		String methodName = method.getName();

		if (methodName.startsWith("find") || methodName.startsWith("get")) {
			try {
				ret = invocationContext.proceed();
			} catch (NoResultException nre) {
				log.warn("{} error : {}", methodName, nre.getMessage());
				Class<?> clazz = method.getReturnType();
				if (Collection.class.isAssignableFrom(clazz)) {
					if (List.class.isAssignableFrom(clazz)) {
						ret = Collections.EMPTY_LIST;
					} else if (Set.class.isAssignableFrom(clazz)) {
						ret = Collections.EMPTY_SET;
					} else if (Map.class.isAssignableFrom(clazz)) {
						ret = Collections.EMPTY_MAP;
					}
				} else {
					// doNothing, ret is null
				}
			}
		} else {
			ret = invocationContext.proceed();
		}

		return ret;
	}
}
